package com.espirit.eap.manager;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.espirit.eap.sa.LoginUserService;
import com.googlecode.cswish.Config;
import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.exception.ApplicationException;
import com.googlecode.cswish.struts.hibernate.DbTools;
import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.util.FileUtil;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

@Service
public class DbBackupHistoryService {

	private static Logger logger = LoggerFactory.getLogger(DbBackupHistoryService.class);
	
	@Resource
	private GenericService genericService;
	
	@Resource
	private LoginUserService loginUserService;
	
	@Resource
	private Config config;
	
	@Transactional
	public boolean deleteList(List<DbBackupHistory> results) {
    	boolean ret = true;
    	if (results != null) {
			for (DbBackupHistory theModel : results) {
				if (theModel != null) {
					ret &= delete(theModel);
				}
			}
    	}
    	return ret;
    }

    public boolean delete(DbBackupHistory model) {
    	String dbBackupDir = getDbBackupDir();
    	String filename = dbBackupDir + model.getBackupFilename();
    	FileUtil.delete(dbBackupDir, filename);
    	return genericService.delete(model);
    }
	
	@Rest(type="update")
	public void backupDbAndDownload() {
		String backupFilename = backupDb();
		if (backupFilename != null) {
			HttpServletResponse response = ServletActionContext.getResponse();
			FileUtil.export(response, backupFilename);
		}
	}
	
	@Rest(type="search")
	public Result download(DbBackupHistory model) {
		model = genericService.load(model);
		HttpServletResponse response = ServletActionContext.getResponse();
		String backupFilename = getDbBackupDir() + model.getBackupFilename();
		FileUtil.export(response, backupFilename);
		return null;
	}
	
	private String getDbBackupDir() {
		return config.getBackupDir() +   "db/";
	}
	
	@Rest(type="update")
	public String backupDb() {
		String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime()) + ".sql";
		
		String backupFilename = getDbBackupDir() + filename;
		if (logger.isDebugEnabled()) {
			logger.debug("begin backup, ouput file:" + backupFilename);
		}
		boolean ret = DbTools.getInstance().backup(backupFilename, null);
		
		if (ret) {
			DbBackupHistory model = new DbBackupHistory();
			model.setBackupFilename(filename);
			model.setCreateOn(Calendar.getInstance().getTime());
			
			genericService.add(model);
		}
		return ret ? backupFilename : null;
	}
	
	@Rest(type="update")
	public void restoreDb(DbBackupHistory model) {
		model = genericService.load(model);
		String dbBackupDir = getDbBackupDir();
		String filename = dbBackupDir + model.getBackupFilename();
		String siteName = loginUserService.getCurrentWebsite().getName();
		if (new File(filename).exists()) {
			DbTools.getInstance().restore(filename, siteName);
		} else {
			throw new ApplicationException("备份文件不存在");
		}
	}
}
